package com.web.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.web.pojo.vo.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败返回JSON格式数据给前端
 * @Author: wws
 * @Date: 2021/2/5 22:14
 * describe:
 */
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        CommonResult commonResult;
        if ("Bad credentials".equals(e.getMessage())){
            commonResult=CommonResult.fail("密码错误");
        }else {

            commonResult=CommonResult.fail(e.getMessage());
        }

        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(commonResult));
    }
}
